﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCSoict.Models;
using Newtonsoft.Json;

namespace MVCSoict.Controllers
{
    public class RoleController : Controller
    {
        private staffsoictEntities1 db = new staffsoictEntities1();
        private JsonSerializerSettings jsonSettings = new JsonSerializerSettings()
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        };
        // GET: /Role/
        public ActionResult Index()
        {
            return View(db.Roles.ToList());
        }

        public string Select(string keyword, int page, int pagesize)
        {
            string jsonResult = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "role_select"))
                {
                    try
                    {
                        using (var context = new staffsoictEntities1())
                        {
                            var roles = from r in context.Roles
                                        where r.name.Contains(keyword) || r.description.Contains(keyword)
                                        orderby r.id
                                        select r;

                            var pageData = roles.Skip((page - 1) * pagesize).Take(pagesize).ToList();
                            foreach (var ro in pageData)
                            {
                                jsonResult += JsonConvert.SerializeObject(ro, jsonSettings);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        jsonResult = ex.Message;
                    }
                }
            }
            return jsonResult;
        }

        public string GetNextId()
        {
            var roles = from r in db.Roles
                        orderby r.id
                        select r;
            int count = roles.Count();
            string id = string.Empty;
            string nextid = string.Empty;
            int delta = 0;
            if (count > 0)
            {
                id = roles.ToList()[count - 1].id;
                int y = Convert.ToInt32(id[4].ToString());
                if (y < 9)
                {
                    delta = 1;
                }
                if (y >= 9 && y < 99)
                {
                    delta = 2;
                }
                if (y >= 99 && y < 999)
                {
                    delta = 3;
                }
                for (int i = 0; i < (id.Count() - delta); i++)
                {
                    nextid += id[i].ToString();
                }   
                nextid += (y + 1).ToString();
            }
            else
            {
                nextid = "R0000";
            }
            return nextid;
        }

        public string Add([Bind(Include = "name,description")] Role role)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "role_add"))
                {
                    try
                    {
                        role.id = GetNextId();
                        db.Roles.Add(role);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(role, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string Xoa(string id)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "role_xoa"))
                {
                    Role role = db.Roles.Find(id);
                    try
                    {
                        db.Roles.Remove(role);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(role, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        //tested
        public string Update([Bind(Include = "id,name,description")] Role role)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "role_update"))
                {
                    try
                    {
                        db.Entry(role).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(role, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string Matrix(string keyword)
        {
            string res = string.Empty;
            string resRole = "Role:";
            string resAction = "Action:";
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "role_matrix"))
                {
                    try
                    {
                        using (var context = new staffsoictEntities1())
                        {
                            var roles = from r in context.Roles
                                        where r.name.Contains(keyword) || r.description.Contains(keyword)
                                        //orderby r.id
                                        select r;
                            foreach (var role in roles.ToList<Role>())
                            {
                                resRole += JsonConvert.SerializeObject(role.id);
                            }

                            var actions = from a in context.Actions
                                          //where a.name.Contains() || a.description.Contains()
                                          //orderby a.id
                                          select a;
                            foreach (var action in actions)
                            {
                                resAction += JsonConvert.SerializeObject(action.id);
                            }

                            int countRole = roles.Count();
                            int countAction = actions.Count();
                            string[,] matrix = new string[countRole, countAction];
                            for (int i = 0; i < countRole; i++)
                            {
                                for (int j = 0; j < countAction; j++)
                                {
                                    matrix[i, j] = "0";
                                }
                            }

                            int[,] refs = new int[countRole, countAction];
                            int indexAction = 0;
                            for (int i = 0; i < countRole; i++)
                            {
                                var actionsNRole = roles.ToList<Role>()[i].Actions.ToList<MVCSoict.Models.Action>();
                                int countActionNrole = actionsNRole.Count;
                                for (int j = 0; j < countActionNrole; j++)
                                {
                                    for (int k = 0; k < countAction; k++)
                                    {
                                        if (actionsNRole[j].id.Equals(actions.ToList<MVCSoict.Models.Action>()[k].id))
                                        {
                                            matrix[i, k] = "1";
                                        }
                                    }
                                }
                            }

                            res = JsonConvert.SerializeObject(matrix, jsonSettings);
                        }
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return resRole + resAction + res;
        }

        public string Get(string id)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "role_get"))
                {
                    try
                    {
                        var roles = from r in db.Roles
                                    where r.id.Equals(id)
                                    select r;
                        if ((roles.ToList<Role>().Count() > 0))
                            res = JsonConvert.SerializeObject(roles.ToList<Role>()[0], jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string AddAction(string aid, string rid)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "role_addaction"))
                {
                    try
                    {
                        Role role = db.Roles.Find(rid);
                        MVCSoict.Models.Action action = db.Actions.Find(aid);
                        role.Actions.Add(action);
                        db.Entry(role).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(action, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string RemoveAction(string rid, string aid)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "role_removeaction"))
                {
                    try
                    {
                        Role role = db.Roles.Find(rid);
                        MVCSoict.Models.Action action = db.Actions.Find(aid);
                        role.Actions.Remove(action);
                        db.Entry(role).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(1, jsonSettings);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            return res;
        }

        // GET: /Role/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Role role = db.Roles.Find(id);
            if (role == null)
            {
                return HttpNotFound();
            }
            return View(role);
        }

        // GET: /Role/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Role/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "id,name,description")] Role role)
        {
            if (ModelState.IsValid)
            {
                db.Roles.Add(role);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(role);
        }

        // GET: /Role/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Role role = db.Roles.Find(id);
            if (role == null)
            {
                return HttpNotFound();
            }
            return View(role);
        }

        // POST: /Role/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "id,name,description")] Role role)
        {
            if (ModelState.IsValid)
            {
                db.Entry(role).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(role);
        }

        // GET: /Role/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Role role = db.Roles.Find(id);
            if (role == null)
            {
                return HttpNotFound();
            }
            return View(role);
        }

        // POST: /Role/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            Role role = db.Roles.Find(id);
            db.Roles.Remove(role);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
